package com.rzico.sbl.ui.member

import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberDetailBinding
import com.rzico.sbl.other.showMemoDialog
import com.rzico.sbl.ui.mine.WalletCoinActivity
import com.rzico.sbl.ui.order.OrderShipWhereActivity
import com.rzico.sbl.ui.order.OrderShipWhoActivity
import com.rzico.sbl.ui.statistic.BillDetailActivity
import com.rzico.sbl.viewmodel.MemberViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.startIncreaseAnimator
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setColor
import com.xinnuo.common_ui.utils.showActionDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

class MemberDetailActivity : BaseActivity(R.layout.activity_member_detail) {

    private val mBinding by lazy { ActivityMemberDetailBinding.bind(getRootView()) }

    private lateinit var mCardId: String
    private lateinit var mMemberId: String
    private lateinit var mMemberPhone: String
    private var mMemberName = ""
    private var mMemberType = ""
    private var mMemberKind = ""
    private val mMemberPay = MutableLiveData("")
    private var mMemberLimit = ""
    private var mMemberWhere = ""
    private var mMemberWho = ""

    override fun getViewModel() = get<MemberViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        getData()
    }

    override fun initListener() {
        mCardId = intent.getExtra("cardId")
        mMemberId = intent.getExtra("memberId")
        mMemberPhone = intent.getExtra("memberPhone")

        mBinding.apply {
            memberMoneyLl.oneClick {
                showActionDialog(
                    "修改余额", "交易明细"
                ) { index, _ ->
                    when (index) {
                        0 -> {
                            lifecycleScope
                                .launch(Dispatchers.Main.immediate) {
                                    delay(300)

                                    showMemoDialog(
                                        title = "修改余额",
                                        hint = "请输入要修改的金额",
                                        inputType = "double",
                                        default = memberMoney.content
                                    ) {
                                        memberInfo(
                                            type = "12",
                                            result = it,
                                            "id" to mCardId,
                                            "balance" to it
                                        )
                                    }
                                }
                        }

                        1 -> {
                            startActivityEx<MemberBalanceActivity>("cardId" to mCardId)
                        }
                    }
                }
            }

            memberCoinLl.oneClick {
                showActionDialog(
                    "修改金币", "交易明细"
                ) { index, _ ->
                    when (index) {
                        0 -> {
                            lifecycleScope
                                .launch(Dispatchers.Main.immediate) {
                                    delay(300)

                                    showMemoDialog(
                                        title = "修改金币",
                                        hint = "请输入要修改的数量",
                                        inputType = "number",
                                        default = memberCoin.content
                                    ) {
                                        memberInfo(
                                            type = "13",
                                            result = it,
                                            "id" to mCardId,
                                            "point" to it
                                        )
                                    }
                                }
                        }

                        1 -> {
                            startActivityEx<WalletCoinActivity>("cardId" to mCardId)
                        }
                    }
                }
            }

            memberArrearLl.oneClick {
                startActivityEx<BillDetailActivity>(
                    "cardId" to mCardId,
                    "memberId" to mMemberId,
                    "amount" to memberArrear.content
                )
            }

            memberName1.oneClick {
                showMemoDialog(
                    title = "会员名称",
                    hint = "请输入会员名称(10个汉字以内)",
                    default = mMemberName,
                    inputType = "text",
                    canEmpty = false
                ) {
                    memberInfo(
                        type = "1",
                        result = it,
                        "id" to mCardId,
                        "name" to it
                    )
                }
            }

            memberType.oneClick {
                showActionDialog(
                    "个人用户", "企业用户"
                ) { index, hint ->
                    memberInfo(
                        type = "2",
                        result = "${if (index == 0) "family" else "company"},$hint",
                        "id" to mCardId,
                        "cardType" to (if (index == 0) "family" else "company")
                    )
                }
            }

            memberVip.oneClick {
                val vipList = getViewModel()
                    .mVipList
                    .map { it.name }
                    .toTypedArray()

                showActionDialog(*vipList) { index, hint ->
                    memberInfo(
                        type = "3",
                        result = hint,
                        "id" to mCardId,
                        "vip" to "vip$index"
                    )
                }
            }

            memberKind.oneClick {
                showActionDialog(
                    "会员", "推广员"
                ) { index, hint ->
                    memberInfo(
                        type = "4",
                        result = "${if (index == 1) "team" else "member"},$hint",
                        "id" to mCardId,
                        "type" to (if (index == 1) "team" else "member")
                    )
                }
            }

            memberPay.oneClick {
                showActionDialog(
                    "现金", "记账"
                ) { index, hint ->
                    memberInfo(
                        type = "5",
                        result = "${if (index == 1) "monthly" else "immediate"},$hint",
                        "id" to mCardId,
                        "paymentMethod" to (if (index == 1) "monthly" else "immediate")
                    )
                }
            }

            memberLimit.oneClick {
                showMemoDialog(
                    title = "记账额度",
                    hint = "请输入最大可记账金额",
                    inputType = "double",
                    default = mMemberLimit
                ) {
                    memberInfo(
                        type = "10",
                        result = it,
                        "id" to mCardId,
                        "maxLimit" to it
                    )
                }
            }

            memberLimitGoods.oneClick {
                startActivityEx<MemberBillActivity>("cardId" to mCardId)
            }

            memberMin.oneClick {
                showMemoDialog(
                    title = "最小起订量",
                    hint = "请输入最小起订数量",
                    inputType = "number"
                ) {
                    memberInfo(
                        type = "11",
                        result = it,
                        "id" to mCardId,
                        "minLimit" to (it.takeIf { it.intValue > 0 } ?: "0")
                    )
                }
            }

            memberUp.oneClick {
                startActivityEx<MemberPromoterActivity>()
            }

            memberMemoLl.oneClick {
                showMemoDialog(
                    title = "客户备注",
                    hint = "请输入备注信息",
                    inputType = "longText",
                    default = memberMemo.content
                ) {
                    memberInfo(
                        type = "6",
                        result = it,
                        "id" to mCardId,
                        "memo" to it
                    )
                }
            }

            memberClear.oneClick {
                memberInfo(
                    type = "9",
                    result = "无",
                    "id" to mCardId,
                    "shippingId" to "-1",
                    "adminId" to "-1",
                )
            }

            memberWhere.oneClick {
                startActivityEx<OrderShipWhereActivity>()
            }

            memberWho.oneClick {
                if (mMemberWhere.isEmpty()) {
                    showToast("请选择配送店铺")
                    return@oneClick
                }

                startActivityEx<OrderShipWhoActivity>("shopId" to mMemberWhere)
            }

            memberMore.oneClick {
                startActivityEx<MemberMoreActivity>(
                    "cardId" to mCardId,
                    "memberId" to mMemberId,
                    "memberPhone" to mMemberPhone
                ) { clearTop() }
            }

            mMemberPay
                .observe(getLifecycleOwner()) {
                    memberLimit.isVisible = it == "monthly"
                    memberLimitGoods.isVisible = it == "monthly"
                }
        }

        observe<String>("orderShip") {
            val items = it.split(",")
            when (items[0]) {
                "shop" -> {
                    memberInfo(
                        type = "7",
                        result = "${items[1]},${items[2]}",
                        "id" to mCardId,
                        "shippingId" to items[1]
                    )
                }

                "admin" -> {
                    memberInfo(
                        type = "8",
                        result = "${items[1]},${items[2]}",
                        "id" to mCardId,
                        "adminId" to items[1]
                    )
                }
            }
        }

        observe<String>("promoterChange") {
            val items = it.split(",")

            memberInfo(
                type = "14",
                result = "${items[0]},${items[1]}",
                "id" to mCardId,
                "promoterId" to items[0]
            )
        }
    }

    /**
     * 会员修改
     */
    private fun memberInfo(
        type: String,
        result: String,
        vararg params: Pair<String, Any>
    ) {
        getViewModel()
            .memberModify(*params)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    showToast("会员信息修改成功！")

                    mBinding.apply {
                        when (type) {
                            "1" ->
                                result.also {
                                    mMemberName = it
                                    memberName.text = it
                                    memberName1.setRightString(it)
                                }

                            "2" ->
                                result.split(",")
                                    .also {
                                        mMemberType = it[0]
                                        memberType.setRightString(it[1])
                                    }

                            "3" -> memberVip.setRightString(result)
                            "4" ->
                                result.split(",")
                                    .also {
                                        mMemberKind = it[0]
                                        memberKind.setRightString(it[1])
                                    }

                            "5" ->
                                result.split(",")
                                    .also {
                                        mMemberPay.value = it[0]
                                        memberPay.setRightString(it[1])
                                    }

                            "6" -> memberMemo.text = result
                            "7" ->
                                result.split(",")
                                    .also {
                                        mMemberWhere = it[0]
                                        mMemberWho = ""
                                        memberWhere.setRightString(it[1])
                                        memberWho.setRightString("无")
                                    }

                            "8" ->
                                result.split(",")
                                    .also {
                                        mMemberWho = it[0]
                                        memberWho.setRightString(it[1])
                                    }

                            "9" -> {
                                mMemberWhere = ""
                                mMemberWho = ""
                                memberWhere.setRightString(result)
                                memberWho.setRightString(result)
                            }

                            "10" -> {
                                mMemberLimit = result

                                if (result.doubleValue > 0)
                                    memberLimit.setRightString("${result.formatDecimalWhenHave()} 元")
                                else
                                    memberLimit.setRightString("不限额")
                            }

                            "11" -> {
                                if (result.doubleValue > 0)
                                    memberMin.setRightString(result)
                                else
                                    memberMin.setRightString("不限")
                            }

                            "12" ->
                                memberMoney
                                    .startIncreaseAnimator(
                                        to = result.floatValue,
                                        milliseconds = 300
                                    )

                            "13" ->
                                memberCoin
                                    .startIncreaseAnimator(
                                        to = result.intValue,
                                        milliseconds = 300
                                    )

                            "14" ->
                                result.split(",")
                                    .also {
                                        memberUp.setRightString(it[1])
                                    }
                        }
                    }

                    // 刷新会员列表标签
                    LiveEventBus
                        .get("memberList")
                        .post("refresh")
                }
            )
    }

    /**
     * 会员详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .memberDetail(mCardId)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val objOuter = JSONObject(result)
                    val obj = objOuter.optJSONObject("card") ?: JSONObject()

                    mMemberType = obj.optNotNull("cardType")
                    mMemberKind = obj.optNotNull("type")
                    mMemberPay.value = obj.optNotNull("paymentMethod")
                    mMemberWhere = obj.optNotNull("shippingId")

                    mBinding.apply {
                        // 名称
                        obj.optNotNull("name")
                            .apply {
                                mMemberName = this

                                memberName.text = this
                                memberName1.setRightString(this)
                            }

                        // 头像
                        memberLogo.loadCircleImage(
                            obj.optString("logo"),
                            R.mipmap.default_user
                        )
                        // 手机号
                        memberPhone.text = obj.optNotNull("mobile")
                        // 编号
                        memberNum.setColor(
                            "NO.${obj.optNotNull("code")}",
                            "NO.",
                            "#FFA200"
                        )

                        // 余额
                        memberMoney.startIncreaseAnimator(
                            to = obj.optNotNull("balance").floatValue,
                            milliseconds = 300
                        )
                        // 金币
                        memberCoin.startIncreaseAnimator(
                            to = obj.optNotNull("point").intValue,
                            milliseconds = 300
                        )
                        // 欠款
                        memberArrear.startIncreaseAnimator(
                            to = obj.optNotNull("arrears").floatValue,
                            milliseconds = 300
                        )

                        // 用户类型
                        memberType.setRightString(
                            when (mMemberType) {
                                "company" -> "企业用户"
                                else -> "个人用户"
                            }
                        )
                        // 等级
                        memberVip.setRightString(
                            obj.optNotNull("vip").uppercase()
                        )
                        // 类型
                        memberKind.setRightString(
                            when (mMemberKind) {
                                "team" -> "推广员"
                                else -> "会员"
                            }
                        )
                        // 支付方式
                        memberPay.setRightString(
                            when (mMemberPay.value) {
                                "monthly" -> "记账"
                                else -> "现金"
                            }
                        )

                        // 记账额度
                        obj.optNotNull("maxLimit")
                            .also { mMemberLimit = it }
                            .doubleValue
                            .also {
                                if (it > 0) memberLimit.setRightString("${it.formatDecimalWhenHave()} 元")
                                else memberLimit.setRightString("不限额")
                            }

                        // 最小起订
                        obj.optNotNull("minLimit")
                            .intValue
                            .also {
                                if (it > 0) memberMin.setRightString("$it")
                                else memberMin.setRightString("不限")
                            }

                        // 推广员
                        memberUp.setRightString(obj.optNotEmpty("promoter", "无"))
                        // 备注
                        memberMemo.text = obj.optNotNull("memo")

                        // 指定派单
                        memberWhere.setRightString(obj.optNotEmpty("shippingName", "无"))
                        val objAdmin = obj.optJSONObject("admin") ?: JSONObject()
                        mMemberWho = objAdmin.optNotNull("id")
                        memberWho.setRightString(objAdmin.optNotEmpty("name", "无"))
                    }
                }
            )
    }

}